//
//  CoinRowView.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/21.
//

import SwiftUI

struct CoinRowView: View {
    let coin: CoinModel

    let showHoldingsColumn: Bool

    var body: some View {
        HStack(spacing: 0) {
            leftColumn
            Spacer()
            if showHoldingsColumn {
                centerColumn
            }
//            Spacer()
            rightColum
        }
        .font(.subheadline)
        .background {
            Color.theme.background // 为了navigationLink可点击 一整行 （中间是Spacer点不到）
        }
    }
}

#Preview() {
    CoinRowView(coin: Preview.dev.coin, showHoldingsColumn: true)
        .previewLayout(.sizeThatFits)
}

#Preview("Dark") {
    CoinRowView(coin: Preview.dev.coin, showHoldingsColumn: true)
        .previewLayout(.sizeThatFits) // unwork
        .preferredColorScheme(.dark)
}

extension CoinRowView {
    private var leftColumn: some View {
        HStack(spacing: 0) {
            Text("\(coin.rank)")
                .font(.caption)
                .foregroundStyle(Color.theme.secondaryText)
                .frame(minWidth: 30)

            CoinImageView(coin: coin)
                .frame(width: 30, height: 30)
            Text(coin.symbol.uppercased())
                .font(.headline)
                .padding(.leading, 6)
                .foregroundStyle(Color.theme.accent)
        }
    }

    private var centerColumn: some View {
        VStack(alignment: .trailing) {
            Text(coin.currentHoldingsValue.asCurrencyWith2Decimals())
                .bold()
            Text((coin.currentHoldings ?? 0).asNumberString())
        }
        .foregroundStyle(Color.theme.accent)
    }

    private var rightColum: some View {
        VStack(alignment: .trailing) {
            // asCurrencyWith6Decimals  exition Double 的方法
            Text(coin.currentPrice.asCurrencyWith6Decimals())
                .bold()
                .foregroundStyle(Color.theme.accent)
            Text(coin.priceChangePercentage24H?.asPercentString() ?? "0.00%")
                .foregroundStyle(
                    (coin.priceChangePercentage24H ?? 0) >= 0 ?
                        Color.theme.green : Color.theme.red
                )
        }
//            .padding(.trailing)
        .frame(width: UIScreen.main.bounds.width / 3.5, alignment: .trailing)
    }
}
